<template>
  <div class="edit">

    <!--S主体-->
    <cube-scroll ref="scroll" :style="{height:page_height+'px'}">
      <cube-form ref="form" id="form" :model="data" :schema="form" :options="formOptios" @submit="sendSubmit">
        <cube-form-item :field="form.fields[0]"></cube-form-item>
        <cube-form-item :field="form.fields[1]"></cube-form-item>
        <cube-form-item :field="form.fields[2]"></cube-form-item>
        <cube-form-item :field="form.fields[3]">
          <div class="sell-range" @click="goSelectSellRange">
            <template v-if="sell_range.length > 0">
              <div v-for="item in sell_range">{{item.name}}</div>
            </template>
            <template v-else><b>选择经营范围</b></template>
          </div>
        </cube-form-item>

        <!--S定位-->
        <cube-form-item :field="form.fields[4]">
          <div id="location">
            <div class="map" @touchstart.stop>
                <div id="map"></div>
            </div>
            <cube-button @click="clickLocation">定位</cube-button>
          </div>
        </cube-form-item>
        <!--E定位-->

      </cube-form>

    </cube-scroll>
    <!--E主体-->

    <!--返回首页--><div id="back-index" v-if="doing == 'edit'"><router-link class="back-a" to="/" replace></router-link></div>

    <!--S创建修改门店按钮-->
    <div id="submit" ref="footer">
      <cube-button type="submit" :primary="true" @click="submit">
        <template v-if="doing =='add'">创建门店</template>
        <template v-else>修改门店</template>
      </cube-button>
    </div>
    <!--E创建修改门店按钮-->

    <!--S选择经营范围区域-->
    <div id="select-range" v-if="select_range_show" :class="show_hide_anim">
      <h2>选择经营范围</h2>

      <!--S搜索-->
      <div class="search">
        <form action="" method="post" @submit.prevent="searchSellRange">
          <cube-input v-model.trim="search_value" placeholder="搜索经营范围" type="search" @input="inputSearchSellRange"></cube-input>
        </form>
      </div>
      <!--E搜索-->

      <!--S已选的经营范围-->
      <div class="already" v-if="sell_range.length">
        <h3>已选</h3>
        <cube-scroll direction="horizontal" ref="alreadyScroll" :options="{click:false}">
          <ul>
            <li v-for="(item,index) in sell_range" @click="clickUnselectLi(index)">{{item.name}}</li>
          </ul>
        </cube-scroll>
      </div>
      <!--E已选的经营范围-->

      <cube-scroll class="select-range-scroll" ref="selectRangeScroll">

        <!--S已选择的经营范围-->
        <ul class="select" v-if="all_sell_range.length > 0">
          <li v-for="(item,index) in all_sell_range" :class="item.selected==1 ? 'selected' : ''" @click="clickSelectLi(index)">{{item.name}}</li>
        </ul>
        <h4 v-else style="display:block;width:355px;text-align:center;margin-top:10px;color:#d4d4d4;">暂无相关选项</h4>
        <!--E已选择的经营范围-->

      </cube-scroll>

      <!--S底部控制-->
      <div class="control">
        <cube-button :primary="true" @click="closeSelectRange">确认</cube-button>
      </div>
      <!--E底部控制-->
    </div>
    <!--E选择经营范围区域-->

  </div>
</template>

<script>
import store from '../../store.js';
import common from '../../public/common.js';
export default {
  name: 'edit',   //修改或者新增门店
  data(){
    var self = this;
    return {
      page_height:store.state.height,
      doing:'add',   //新增门店或者修改门店
      store_id:store.state.store.store_id,  //门店id
      //S表单数据
      data: {
        name: '',  //门店名字
        logo_result: [], //门店logoUpload组件返回的数据
        logo: '',  //门店logo
        address: '',  //门店地址
      },
      //E表单数据
      //S表单结构
      formOptios:{layout:'fresh'},  //表单配置
      form:{
        fields:[
          {
            label:'门店名称',
            type:'input',
            modelKey:'name',
            props: {
              placeholder: '门店名称'
            },
            rules:{
              required:true,
              max:50
            }
          },
          {
            label:'门店logo',
            type:'upload',
            modelKey:'logo_result',
            props:{
              max:1,
              action:{
                target:sysinfo.url,
                data:{
                  pages:'file',
                  doing:'uploadImage'
                },
                //上传成功
                checkSuccess(res){
                  if(res.status == 'success'){
                    self.data.logo = res.data;
                    return true;
                  }else{
                    return false;
                  }
                }
              },
            },
            rules:{
              required:true
            }
          },
          {
            label:'门店地址',
            type:'textarea',
            modelKey:'address',
            props:{
              placeholder: '门店地址',
            },
            rules:{
              required:true,
              max:255
            },
            events:{
              blur(){
                window.scroll(0,0);
              }
            }
          },
          {
            label:'经营范围',
            modelKey:'sell_range'
          },
          {
            label:'门店定位(请在门店内进行此操作，方便用户找到门店)',
            modelKey:'location'
          }
        ]
      },
      //E表单结构
      //S选择经营范围
      select_range_show:false,
      show_hide_anim:'animated slideInUp faster',   //显示隐藏动画
      search_value:'',  //搜索经营范围的value
      all_sell_range:[],   //系统所有经营范围类型
      sell_range:[],   //选择的经营范围类型
      //E选择经营范围
      //门店定位
      location:[],  //门店定位经纬度
      map:{  //地图数据
        map:null,  //地图对象
        location:null,  //定位对象
        mark:null   //门店标记对象
      }
    }
  },
  computed:{
    str_sell_range(){
      var id_arr = [];
      this.sell_range.forEach((item)=>{
        id_arr.push(item.id);
      });
      return id_arr.join();
    },
    str_location(){
      return JSON.stringify(this.location);
    }
  },
  created(){
    let {doing} = this.$route.params;
    this.doing = doing;
  },
  mounted(){
    common.store()
            .then((res)=>{
              if(res){
                if(store.state.store.position_id != 0){
                  if(!store.state.store.authority.includes('store')){
                    this.$router.replace('/');
                    return;
                  }
                }
                this.store_id = res.store_id;
                this.data = {
                  name: res.name,  //门店名字
                  logo_result: [{
                    status:'success',
                    url:sysinfo.attachurl_local+res.logo,
                  }], //门店logoUpload组件返回的数据
                  logo: res.logo,  //门店logo
                  address: res.address,  //门店地址
                }
                this.sell_range = res.sell_range;
                this.location = res.location;
              }
              this.allSellRange();
            })
            .then(()=>{
              this.loadMap();
            })
            .catch(error=>console.log(error));
    if(this.doing == 'add' && this.store_id != 0){
      this.$router.replace('/edit/edit');
    }
    this.$nextTick(()=>{
      setTimeout(()=>{
        this.page_height = document.documentElement.clientHeight - this.$refs.footer.getBoundingClientRect().height;
      },100);
    });
  },
  methods:{
    //提交
    submit(){
      this.$refs.form.submit();
    },
    //发送提交
    sendSubmit(){
      if(this.sell_range.length <= 0){
        this.$createToast({
          txt: '至少选择一个经营类型',
          type: 'txt',
          time:700
        }).show();
        return;
      }
      if(this.location.length <= 0){
        this.$createToast({
          txt: '请定位门店地址',
          type: 'txt',
          time:700
        }).show();
        return;
      }
      let {name,logo,address} = this.data;
      var data = {
        pages:'store',
        doing:this.doing,
        uid:sysinfo.uid,
        data:{
          name,
          logo,
          address,
          sell_range:this.str_sell_range,
          location:this.str_location
        }
      }
      if(this.doing == 'edit'){
        data.store_id = this.store_id;
      }
      this.$http.post(sysinfo.url,Qs.stringify(data))
              .then((res)=>{
                  if(res.data.status == 'success'){
                    var toastText = this.doing == 'add' ? '创建成功' : '修改成功';
                    if(this.doing == 'add'){
                      this.doing = 'edit';
                      this.store_id = res.data.data;
                    }
                    store.set('store',{
                      id:res.data.data,
                      name,
                      logo,
                      address,
                      sell_range:this.sell_range
                    });
                    this.$createToast({
                      time: 1000,
                      txt: toastText,
                      type:'correct'
                    }).show();
                  }else{
                    var toastText = this.doing == 'add' ? '创建失败' : '修改失败';
                    this.$createToast({
                      time: 1000,
                      txt: toastText,
                      type:'error'
                    }).show();
                  }
                })
              .catch(error=>console.log(error));
    },
    //前往选择经营范围
    goSelectSellRange(){
      this.show_hide_anim = 'animated slideInUp faster';
      this.select_range_show = true;
    },
    //关闭选择经营范围区域
    closeSelectRange(){
      this.show_hide_anim = 'animated slideOutDown faster';
      setTimeout(()=>{
        this.select_range_show = false;
      },300);
    },
    //获取所有经营范围
    allSellRange(){
      this.$http.post(sysinfo.url,Qs.stringify({
        pages:'storeManage',
        doing:'findAll',
      }))
              .then((res)=>{
                if(res.data.status == 'success'){
                  this.all_sell_range = res.data.data;
                  if(this.doing == 'edit'){
                    this.initSellRange();
                  }
                }
              })
              .catch(error=>console.log(error));
    },
    //搜索内容改变
    inputSearchSellRange(){
      if(this.search_value == ''){
        this.allSellRange();
      }
    },
    //搜索经营范围
    searchSellRange(){
      if(this.search_value == ''){
        this.$createToast({
          txt: '请输入搜索内容',
          type: 'txt'
        }).show();
      }
      if(this.search_value.length > 10){
        this.$createToast({
          txt: '搜索长度不能大于10位',
          type: 'txt'
        }).show();
      }
      this.$http.post(sysinfo.url,Qs.stringify({
        pages:'storeManage',
        doing:'search',
        keyword:this.search_value
      }))
              .then(res=>{
                if(res.data.status == 'success'){
                  this.all_sell_range = res.data.data;
                  this.initSellRange();
                }else{
                  this.all_sell_range = [];
                }
              })
              .catch(error=>console.log(error));
    },
    //点击li经营范围
    clickSelectLi(index){
      var selected = this.all_sell_range[index].selected;
      if(selected){
        this.all_sell_range[index].selected = 0;
        for(let j=0;j<this.sell_range.length;j++){
          if(this.all_sell_range[index].id == this.sell_range[j].id){
            this.sell_range.splice(j,1);
            break;
          }
        }
      }else{
        if(this.sell_range.length >= 5){
          this.$createToast({
            txt: '最多选择5个经营类型',
            type: 'txt',
            time:700
          }).show();
          return;
        }
        this.all_sell_range[index].selected = 1;
        this.sell_range.push(this.all_sell_range[index]);
      }
    },
    //点击已经选择的Li删除选择的经营类型
    clickUnselectLi(index){
      var sell_range_id = this.sell_range[index].id;
      for(let i=0;i<this.all_sell_range.length;i++){
        if(this.all_sell_range[i].id == sell_range_id){
            this.all_sell_range[i].selected = 0;
            break;
        }
      }
      this.sell_range.splice(index,1);
    },
    //修改门店时候，初始化门店当前设置的经营范围
    initSellRange(){
      this.all_sell_range.forEach((item,index)=>{
        this.sell_range.forEach((itema)=>{
          if(itema.id == item.id){
            this.all_sell_range[index].selected = 1;
          }
        });
      });
    },
    //加载地图
    loadMap(){
      return new Promise((success)=>{
        var mapData = {
          zoom:16,
        }
        this.map.map = new AMap.Map('map',mapData);
        if(this.doing == 'edit' && this.location.length > 0){
          this.map.map.setCenter(this.location);
          this.map.mark = new AMap.Marker({
            position:this.location
          });
          this.map.map.add(this.map.mark);
        }
        success();
      });
    },
    //点击定位按钮
    clickLocation(){
      if(sysinfo.develop && !this.map.location){
        this.createMapLocation();
      }
      if(this.map.mark) this.map.map.remove(this.map.mark);
      this.getLocation()
              .then((position)=>{
                this.location = position;
                this.map.map.setCenter(position);
                this.map.mark = new AMap.Marker({
                  position
                });
                this.map.map.add(this.map.mark);
              })
              .catch(error=>console.log(error));
    },
    //创建高德地图定位对象
    createMapLocation(){
      this.map.location = new AMap.Geolocation({
        showButton:false,
        showMarker:false,
        showCircle:false,
        panToLocation:false
      });
      this.map.map.addControl(this.map.location);
    },
    //定位，如果是开发环境使用高德定位，生产使用微信环境
    getLocation(){
      if(sysinfo.develop){
        return new Promise((success,error)=>{
          this.map.location.getCurrentPosition((status,result)=>{
            if(status == 'complete'){
              success([result.position.lng,result.position.lat]);
            }else{
              error('定位失败');
            }
          });
        });
      }else{
        return new Promise((success,error)=>{
          wx.getLocation({
            type: 'gcj02',
            success:(res)=>{
              success([res.longitude,res.latitude]);
            },
            cancel:function(){
              error('定位失败');
            }
          })
        });
      }
    }
  }
}
</script>

<style scoped>
  .edit{
    padding:0 10px 50px 10px;
    box-sizing: border-box;
  }
  #form{
    margin-top: 5px;
  }
  .sell-range{
    width:100%;
    min-height:40px;
    padding-top:5px;
    box-sizing: border-box;
  }
  .sell-range div{
    display: inline-block;
    padding:5px 10px;
    background: #FC9153;
    color:#fff;
    margin:0 5px 5px 0;
    border-radius:19.5px;
  }
  .sell-range b{
    display: block;
    padding-top:5px;
    color:#ccc;
  }
  #submit{
    position: fixed;
    z-index:100;
    bottom:0;
    left:0;
    width:100%;
  }
  #submit button{
    border-radius: 0;
  }
  #select-range{
    position:fixed;
    z-index:101;
    left:0;
    right:0;
    top:0;
    bottom:0;
    background: #fff;
    padding-bottom: 220px;
  }
  #select-range h2{
    height:40px;
    line-height: 40px;
    background: #FC9153;
    color:#fff;
    text-align: center;
  }
  #select-range .select-range-scroll{
    padding:0 10px;
  }
  #select-range .control{
    position: fixed;
    z-index:100;
    width:100%;
    bottom:0;
  }
  #select-range .search{
    padding:0 10px;
    padding-bottom:10px;
    margin-top: 10px;
  }
  #select-range .already{
    padding:0 10px 10px 10px;
  }
  #select-range .already h3{
    padding:5px 0;
    color:#666;
  }
  #select-range .already ul{
    white-space: nowrap;
  }
  #select-range .already ul li{
    display: inline-block;
    padding:5px 10px;
    margin-right:5px;
    background: #FC9153;
    border-radius: 15px;
    color:#fff;
    font-size:16px;
  }
  #select-range ul.select li{
    float:left;
    background: #fff;
    padding: 5px 10px;
    border:1px solid #ccc;
    margin:0 5px 10px 0;
    border-radius: 15px;
    font-size:16px;
    color:#666;
  }
  #select-range ul.select li.selected{
    background: #FC9153;
    border-color:#fff;
    color:#fff;
  }
  #back-index{
    position: fixed;
    z-index:101;
    bottom:90px;
    right:20px;
    width:40px;
    height:40px;
    border-radius: 40px;
    background: url('../../theme/images/index.svg') #FC9153 no-repeat center 5px;
    background-size:27px;
  }
  #back-index .back-a{
    display: block;
    width:100%;
    height:100%;
  }
  #location .map{
    width:100%;
    height:200px;
    box-sizing: border-box;
  }
  #location .map #map{
    height:200px;
  }
</style>


<style lang="stylus" rel="stylesheet/stylus">
  #select-range .cube-scroll-content
    display: inline-block;
</style>
